<template>
  <div class="article-list">
    <van-pull-refresh
      v-model="refreshing"
      @refresh="getNextPageArticle"
      success-text="刷新成功"
    >
      <van-list
        @load="getNextPageArticle"
        :immediate-check="false"
        v-model="loading"
        :finished="finished"
        finished-text="没有更多了哟~~"
        :error.sync="error"
        error-text="请求失败，点击重新加载"
      >
        <article-item
          v-for="item in articles"
          :key="item.art_id"
          :article-info="item"
        ></article-item>
      </van-list>
    </van-pull-refresh>
  </div>
</template>

<script>
import { getArticlesAPI } from '@/api'
import ArticleItem from './ArticleItem.vue'
export default {
  name: 'ArticleList',
  components: {
    ArticleItem
  },
  props: {
    channelId: [Number, String]
  },
  data () {
    return {
      articles: [],
      loading: false,
      finished: false,
      preTimeStamp: '',
      error: false,
      refreshing: false
    }
  },
  computed: {},
  watch: {},
  created() {
    this.getFirstPageArticle()
  },
  methods: {
    async getFirstPageArticle() {
      try {
        const { data } = await getArticlesAPI(this.channelId, Date.now())
        this.articles = data.data.results
        this.preTimeStamp = data.data.pre_timestamp
      } catch (error) {
        if (error.response?.status === 400) {
          this.$toast.fail(error.response.data.message)
        } else {
          throw error
        }
      }
    },
    async getNextPageArticle() {
      try {
        const { data } = await getArticlesAPI(this.channelId, this.preTimeStamp)
        const results = data.data.results
        if (this.loading) {
          this.articles.push(...results)
        } else {
          this.articles.unshift(...results)
        }
        this.preTimeStamp = data.data.pre_timestamp
        if (this.preTimeStamp === null) {
          this.finished = true
        }
      } catch (error) {
        this.error = true
      } finally {
        this.loading = false
        this.refreshing = false
      }
    }
  }
}
</script>

<style scoped lang="less">
// 添加滚动条
// 定高  overflow:auto
.article-list {
  height: calc(100vh - 100px - 83px - 92px);
  overflow: auto;
  // 滚动槽样式
  &::-webkit-scrollbar {
    width: 10px;
    background-color: transparent;
  }
  // 滚动条样式
  &::-webkit-scrollbar-thumb {
    background-color: #3296fa;
    border-radius: 10px;
  }
}
</style>
